package com.k2data.k2app.service;

import com.k2data.k2app.domain.SysUser;
import com.k2data.k2app.domain.SysUserRole;
import com.k2data.k2app.exception.K2ResponseException;
import com.k2data.k2app.mapper.SysUserRoleMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author lidong 17-3-6.
 */
@Log4j2
@Service
public class SysUserRoleService {


    @Autowired
    public SysUserRoleMapper sysUserRoleMapper;


    @Transactional
    public int updateByUser(SysUser sysUser) throws K2ResponseException {
        if(sysUser.getId() != null){
            sysUserRoleMapper.deleteByUserId(sysUser.getId());
        }
        //和角色关联
        List<SysUserRole> list = new ArrayList<>();
        int num = 0;
        if(sysUser.getRoleIds() != null){
            List roles = sysUser.getRoleIds();
            if(roles != null){
                roles.stream().forEach(item -> {
                    SysUserRole sysUserRole = new SysUserRole();
                    sysUserRole.setUserId(sysUser.getId());
                    sysUserRole.setRoleId(Long.parseLong(item.toString()));
                    list.add(sysUserRole);
                });
            }

            if(list.size()>0){
                num = sysUserRoleMapper.insertBatch(list);
            }
        }
        return num;
    }
}
